package com.itheima.stock.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.stock.common.domain.*;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.pojo.StockBusiness;
import com.itheima.stock.service.StockService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.req.PageResult;
import com.itheima.stock.vo.resp.R;


import lombok.extern.log4j.Log4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service

public class StockServiceImpl implements StockService {
    @Autowired
    private StockBusinessMapper stockBusinessMapper;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;

    @Autowired
    private StockInfoConfig stockInfoConfig;

    //板块mapper
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;

    //do:个股mapper
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;

    @Override
    public List<StockBusiness> findAll() {
        return stockBusinessMapper.getAll();
    }

    @Override
    public R<List<InnerMarketDomain>> getInnerMarketInfos() {
        //List<String> stockInfos = stockInfoConfig.getInner();
        //获取最近一次股票交易时间
        Date curTime = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //伪数据
        curTime = DateTime.parse("2021-12-26 10:56:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //查询
        List<InnerMarketDomain> list =  stockMarketIndexInfoMapper.findMarketInfoByTimeANdCodes(curTime,stockInfoConfig.getInner());

        return R.ok(list);
    }

    @Override
    public R<List<StockBlockDomain>> getStockBlockInfos() {
        Date curTime1 = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        System.out.println(curTime1);
        Date curTime = DateTime.parse("2021-12-21 10:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockBlockDomain> list = stockBlockRtInfoMapper.findBlockInfoByVol(curTime);
        return R.ok(list);
    }

    @Override
    public R<List<StockUpdownDomain>> getStockUpDownInfos() {
        //定义伪数据的当前时间
        Date curTime = DateTime.parse("2021-12-30 09:43:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockUpdownDomain> list = stockRtInfoMapper.getStockUpDownInfos(curTime);
        return R.ok(list);
    }

    //分页查询
    @Override
    public R<PageResult<StockUpdownDomain>> getStockByPage(Integer page, Integer pageSize) {
//        PageHelper.startPage(page,pageSize);
//        Date curTime = DateTime.parse("2021-12-30 09:43:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
//        List<StockUpdownDomain> list = stockRtInfoMapper.getStockByPage();
//        //构建pagehelper分页详情对象
//        PageInfo<StockUpdownDomain> pageInfo = new PageInfo<>(list);
//        //转化为自定义分页数据
//        PageResult<StockUpdownDomain> pageResult = new PageResult<>(pageInfo);
//        return R.ok(pageResult);


        PageHelper.startPage(page, pageSize);
        List<StockUpdownDomain> list = stockRtInfoMapper.getStockByPage();
        PageInfo<StockUpdownDomain> pageInfo = new PageInfo<>(list);
        PageResult<StockUpdownDomain> pageResult = new PageResult<>(pageInfo);
        return R.ok(pageResult);



    }

    @Override
    public R<Map> getStockUpdownCount() {
        //获取当前交易时间点
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        //获取截至时间点
        Date endTime = dateTime.toDate();
        //获取endTime的开盘时间
        Date startTime = DateTimeUtil.getOpenDate(dateTime).toDate();
        //伪数据的当前时间
        Date start = DateTime.parse("2022-01-06 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date end = DateTime.parse("2022-01-06 14:25:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //获取涨停数量
        List<Map> upList = stockRtInfoMapper.getStockUpDownCount(start,end,1);
        System.out.println(upList);
        //跌停数量：
        List<Map> downList = stockRtInfoMapper.getStockUpDownCount(start,end,2);
        System.out.println(downList);
        HashMap<String, List> map = new HashMap<>();
        map.put("upList",upList);
        map.put("downList",downList);

        return R.ok(map);




    }

    @Override
    public void exportStockInfoExcel(HttpServletResponse resp, Integer page, Integer pageSize) {
        try {
            //设置响应数据类型：
            resp.setContentType("application/vnd.ms-excel");
            //设置相应数据编码格式
            resp.setCharacterEncoding("utf-8");
            //设置默认文件名
            //设置防止中文乱码：
            String filename = URLEncoder.encode("股票详情", "utf-8");

            resp.setHeader("content-disposition","attachment;filename="+filename+".xlsx");
            PageHelper.startPage(page,pageSize);
            List<StockUpdownDomain> list = stockRtInfoMapper.getStockByPage();
            //给前端相应数据：
            EasyExcel.write(resp.getOutputStream(),StockUpdownDomain.class).sheet("aaa").doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //大盘成交量对比
    @Override
    public R<Map<String, List>> getTradeVolT_1() {
        //获取最新交易时间点
        DateTime tDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        Date tEndDate = tDateTime.toDate();
        //获取开盘时间
        Date tOpenDate = DateTimeUtil.getOpenDate(tDateTime).toDate();
        //获取t-1的截止时间和开盘时间
        DateTime preDateTime = DateTimeUtil.getPreviousTradingDay(tDateTime);
        Date preDate = tDateTime.toDate();
        Date preOpDateTime = DateTimeUtil.getOpenDate(preDateTime).toDate();

        Date tEndTime = DateTime.parse("2022-01-03 13:35:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date tStartTime = DateTime.parse("2022-01-03 9:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date preEndTime = DateTime.parse("2022-01-02 13:35:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date preStartTime = DateTime.parse("2022-01-02 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

        //获取T日成交量数据
        List<Map> tList = stockMarketIndexInfoMapper.getTradeVolT(stockInfoConfig.getInner(),tStartTime,tEndTime);
        //获取t-1日成交量数据
        List<Map> t_1List = stockMarketIndexInfoMapper.getTradeVolT(stockInfoConfig.getInner(),preStartTime,preEndTime);

        Map<String,List> data = new HashMap();
        data.put("volList",tList);
        data.put("yesVolList",t_1List);

        return R.ok(data);
    }

    @Override
    public R<Map> getStockUpdownScopeNum() {
        //获取当前最新时间
        Date curDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //伪数据
        curDate = DateTime.parse("2022-01-02 13:35:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //查询涨停区间数量
        List<Map> list = stockRtInfoMapper.getStockUpdownScopeNum(curDate);
        //补齐无数据的范围并排序
        List<Map> listOrder = stockInfoConfig.getUpDownRange().stream().map(key-> {
            Optional<Map> title = list.stream().filter(map -> key.equals(map.get("title"))).findFirst();
            //判断map是否存在：
            Map tmp = null;
            if(title.isPresent()){
                tmp=title.get();
            }else {
                tmp=new HashMap();
                tmp.put("title",key);
                tmp.put("count",0);
            }
            return tmp;
        }).collect(Collectors.toList());

        HashMap<Object, Object> map = new HashMap<>();
        String strDate = new DateTime(curDate).toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));
        map.put("time",strDate);

        map.put("infos",listOrder);
        return R.ok(map);
    }

    @Override
    public R<List<Stock4MinuteDomain>> getStockMinuteInfo(String code) {
        //伪数据：当前时间和开盘时间
        Date start = DateTime.parse("2022-01-06 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date end = DateTime.parse("2022-01-06 13:25:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Stock4MinuteDomain> list = stockRtInfoMapper.getStockMinuteInfo(code, start,end);
        return R.ok(list);
    }

    @Override
    public R<List<Stock4EvrDayDomain>> getStock4EvrDay(String code) {
        //获取结束时间和开始时间
        DateTime endDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        Date endDate = endDateTime.toDate();
        //向前推10天
        DateTime startdateTime = DateTimeUtil.getOpenDate(endDateTime.minusDays(10));
        Date  startDate  = startdateTime.toDate();
        //伪数据
        Date start = DateTime.parse("2021-12-10 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date end = DateTime.parse("2022-04-06 13:25:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Stock4EvrDayDomain> list =stockRtInfoMapper.getStock4EvrDay(code, start, end);
        return R.ok(list);
    }
}
